﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;

namespace YTSK.Common
{
    #region data DataGridView相关控制
    /// <summary>
    /// data DataGridView相关控制
    /// </summary>
    class handleDataGrid
    {
        #region 导出Excel--调用后会提示保存文件的路径
        /// <summary>
        /// 导出Excel--调用后会提示保存文件的路径
        /// </summary>
        /// <param name="dv">待导入的datagirdview</param>
        public static void ExportExcel(DataGridView dv)
        {
            SaveFileDialog sf = new SaveFileDialog();
            sf.Filter = "xls文件(*.xls)|*.xls";
            DialogResult dr = sf.ShowDialog();
            if (dr != DialogResult.OK) return;
            string filename = sf.FileName;

            StringBuilder sb = new StringBuilder();
            sb.Append("<html><head><meta content=\"text / html; charset = gb2312\"></head><table border=1><tr>");
            for (int k = 0; k < dv.Columns.Count; k++)
            {
                if (dv.Columns[k].Visible == false)
                { continue; }
                sb.Append(string.Format("<th>{0}</th>", dv.Columns[k].HeaderText));
            }
            sb.Append("</tr>");
            //sb.Append(Environment.NewLine);

            for (int i = 0; i < dv.Rows.Count; i++)
            {
                sb.Append("<tr>");
                for (int j = 0; j < dv.Columns.Count; j++)
                {
                    if (dv.Columns[j].Visible == false)
                    { continue; }
                    object oval = dv.Rows[i].Cells[j].Value;
                    if (oval == null || oval == DBNull.Value) oval = "";
                    string sretrun;
                    switch (dv.Columns[j].DefaultCellStyle.Format)
                    {
                        case "yyyy-MM-dd":
                            DateTime dt0;
                            if (DateTime.TryParse(oval.ToString(), out dt0))
                            { sretrun = dt0.ToString("yyyy-MM-dd"); }
                            else
                            { sretrun = oval.ToString(); }
                            break;
                        case "0":
                        case "@":
                            sretrun = "'" + oval.ToString();
                            break;
                        case "#,##0.00":
                            double dval;
                            if (double.TryParse(oval.ToString(), out dval))
                            {
                                sretrun = dval.ToString("#,##0.00");
                            }
                            else
                            { sretrun = oval.ToString(); }
                            break;
                        default:
                            sretrun = oval.ToString();
                            break;
                    }
                    string cformat = dv.Columns[j].DefaultCellStyle.Format;
                    string excelFormat = "";

                    if (cformat.Length > 0)
                    { excelFormat = string.Format("style='mso-number-format: \"{0}\"; '", cformat); }
                    else
                    {
                        if (sretrun.ObjToString().Length>0 && sretrun.Substring(0, 1) == "0")
                        {
                            excelFormat = string.Format("style='mso-number-format: \"@\"; '");
                        }
                    }

                    sb.Append(string.Format("<td {1}>{0}</td>", sretrun, excelFormat));
                    //sb.Append(dt.Rows[i][j].ToString() + "\t");
                }
                sb.Append("</tr>");
                //sb.Append(Environment.NewLine);
            }
            System.IO.StreamWriter writer1 = new System.IO.StreamWriter(filename, false, Encoding.Default);
            writer1.Write(sb.ToString());
            writer1.Close();
            dr = MessageBox.Show(string.Format("保存成功，文件保存在{0}。是否立即打开？", filename), "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            if (dr == DialogResult.Yes)
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.FileName = filename;
                process.Start();
            }
        }
        #endregion

        #region 初始化dataGridView
        /// <summary>
        /// 初始化dataGridView
        /// </summary>
        /// <param name="formatList">格式模版</param>
        /// <param name="dtv">待初始化的datagridview</param>
        public static void initGrid(List<handleDataGrid_Format> formatList, DataGridView dtv)
        {

            dtv.Columns.Clear();
            dtv.Rows.Clear();
            dtv.ReadOnly = true;
            dtv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
            dtv.ColumnHeadersHeight = 20;

            for (int i = 0; i < formatList.Count; i++)
            {
                var format = formatList[i];
                DataGridViewColumn dgvtb;
                //if (format.cDBName == "selcol")
                //{
                //    dgvtb = new DataGridViewCheckBoxColumn();
                //    var headcell = new DataGridViewColumnHeaderCell();
                //    var aa = new DataGridViewCheckBoxCell ();
                //}
                //else
                //{
                    dgvtb = new DataGridViewTextBoxColumn();
                //}
                dgvtb.DataPropertyName = format.cDBName;
                dgvtb.Name = format.cDBName;
                dgvtb.HeaderText = format.cChinaName;
                switch (format.iAlign)
                {
                    case 1:
                        dgvtb.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
                        break;
                    case 2:
                        dgvtb.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                        break;
                    case 3:
                        dgvtb.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        break;
                }
                dgvtb.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dgvtb.Width = format.iWidth;
                dgvtb.Visible = format.bVisible;
                dgvtb.ReadOnly = format.ReadOnly;
                if (format.formatStr != null && format.formatStr.Length > 0)
                {
                    dgvtb.DefaultCellStyle.Format = format.formatStr;
                }
                dgvtb.DisplayIndex = i;
                dgvtb.SortMode = DataGridViewColumnSortMode.Automatic;
                dtv.Columns.Add(dgvtb);
            }
        }
        #endregion

    }

    #region 格式的模版
    /// <summary>
    /// 格式的模版
    /// </summary>
    class handleDataGrid_Format
    {
        private string _cDBName;
        private string _cChinaName;
        private int _ialign;
        private int _iwidth;
        private bool _bvisible;
        private string _cformat;
        private int _datatype;
        private bool _readonly;
        /// <summary>
        /// 数据源名称
        /// </summary>
        public string cDBName
        {
            get { return _cDBName; }
            set { _cDBName = value; }
        }
        /// <summary>
        /// 显示名称
        /// </summary>
        public string cChinaName
        {
            get { return _cChinaName; }
            set { _cChinaName = value; }
        }
        /// <summary>
        /// 对齐方式-1：左对齐；2：中间对齐；3-右对齐
        /// </summary>
        public int iAlign
        {
            get { return _ialign; }
            set { _ialign = value; }
        }
        /// <summary>
        /// 列宽
        /// </summary>
        public int iWidth
        {
            get { return _iwidth; }
            set { _iwidth = value; }
        }
        /// <summary>
        /// 是否可见
        /// </summary>
        public bool bVisible
        {
            get { return _bvisible; }
            set { _bvisible = value; }
        }
        /// <summary>
        /// 列的格式化字符串
        /// </summary>
        public string formatStr
        {
            get { return _cformat; }
            set { _cformat = value; }
        }
        /// <summary>
        /// 列的数据格式
        /// </summary>
        public int datatype
        {
            get{ return _datatype; }
            set { _datatype = value; }
        }
        /// <summary>
        /// 列是否只读
        /// </summary>
        public bool ReadOnly
        {
            get { return _readonly; }
            set { _readonly = value; }
        }
    }
    #endregion
    #endregion
}
